<template>
  <div>
    <!-- <h5>this is user manage</h5> -->
    <div class="searchContainer">
      <el-form ref="searchForm" :model="searchForm" :inline="true" :rules="searchKeyRules">
        <el-form-item prop="key">
          <el-input v-model="searchForm.name" placeholder="员工名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('searchForm')">搜索</el-button>
          <el-button @click="resetForm('searchForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="operationBox">
      <el-button type="primary" @click="dialogStaffVisible = true">添加</el-button>
      <el-popover
        ref="popover1"
        placement="bottom"
        title="请选择筛选身份"
        width="200"
        trigger="click"
        popper-class="popper"  
      >
        <el-button type="primary" slot="reference">按身份筛选</el-button>
        <el-select v-model="searchForm.role" clearable>
            <el-option label="小区医生" value="doctor"></el-option>
            <el-option label="维修师傅" value="repair"></el-option>
            <el-option label="居委会" value="committee"></el-option>
        </el-select>
        <div class="btnbox" style="margin:10px 0;display:flex;justify-content:flex-end;">
          <el-button type="primary" size="mini" @click="searchByRole">搜索</el-button>
        </div>
      </el-popover>
    </div>

    <div class="paginationBox">
      <!-- 员工信息列表 -->
      <el-table :data="staffList">
        <el-table-column
          header-align="center"
          align="center"
          type="index"
          label="序号" 
          :index="handelIndex"
        >
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          prop="name"
          label="员工姓名" >
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          prop="role"
          label="员工身份" >
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          prop="phoneNumber"
          label="联系电话" >
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="登录密码" >
          <template slot-scope="scope">
            <span>{{ staffList[scope.$index].showPassword ? scope.row.password : scope.row.hiddenPassword }}</span> 
            <i class="el-icon-view" @click="view(scope.$index, scope.row)"></i>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          prop="createdTime"
          label="创建时间" >
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          prop="updateTime"
          label="更新时间" >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-popconfirm
              title="确认删除该员工信息？"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <el-button
                size="mini"
                type="danger"
                slot="reference"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="display:flex;justify-content: space-between;">
        <el-pagination
          layout="prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :page-sizes="[5]"
          :current-page="currentPage"
          @current-change="handleCurrentPage"
        >
        </el-pagination>
        <el-pagination
          layout="total, sizes"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[5]"
          @current-change="handleCurrentPage"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 新增员工信息 && 编辑员工信息 -->
    <el-dialog :title="staffForm.id ? '编辑信息' : '新增员工'" :visible.sync="dialogStaffVisible">
      <el-form ref="staffForm" :model="staffForm" label-width="120px" :rules="staffFormRules">
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="staffForm.name" type="text" clearable/>
        </el-form-item> 
        <el-form-item label="登录手机号" prop="phoneNumber">
          <el-input v-model="staffForm.phoneNumber" type="text" clearable/>
        </el-form-item>       
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="staffForm.password" :type="dialogShowPwd ? 'text' : 'password'" clearable>
            <i slot="suffix" class="el-icon-view" @click="dialogShowPwd = !dialogShowPwd"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="员工身份" prop="role">
          <el-select v-model="staffForm.role" >
            <el-option label="小区医生" value="doctor"></el-option>
            <el-option label="维修师傅" value="repair"></el-option>
            <el-option label="居委会" value="committee"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="submitStaffForm('staffForm')">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {formatTime} from '@/utils/utils'
import {validatePhoneNumber,validatePassword,validateName} from "@/utils/validate"

export default {

  data() {
    // 自定义校验规则
    const phoneNumberValidate = (rule,value,callback)=>{
      if(validatePhoneNumber(value)){
        callback()
      }else{
        callback(new Error("请输入正确格式的手机号"))
      }
    };
    const nameValidate = (rule,value,callback)=>{
      if(validateName(value)){
        callback()
      }else{
        callback(new Error("请输入正确格式的姓名"))
      }
    };
    const passwordValidate = (rule,value,callback)=>{
      if(validatePassword(value)){
        callback()
      }else{
        callback(new Error("密码强度过低。至少8位，且包含数字与字母"))
      }
    };
    return {
      searchForm:{
        name:"",
        role:""
      },
      searchKeyRules:{
        key:[{validator:nameValidate,trigger:'blur'}]
      },
      dialogStaffVisible:false,
      staffForm:{
        id:"",
        name:"",
        phoneNumber:"",
        password:"",
        role:"",
        createdTime:""
      },
      loading:false,
      staffFormRules:{
        name:[
          {required:true,validator:nameValidate,trigger:'blur'}
        ],
        phoneNumber:[
          {required:true,validator:phoneNumberValidate,trigger:'blur'}
        ],
        password:[
          {required:true,validator:passwordValidate,trigger:'blur'}
        ],
        role:[
          {required:true,trigger:'blur',message:'请选择员工身份'}
        ]
      },
      total:0,
      pageSize:5,
      currentPage:1,
      role:null,
      staffList:[],
      dialogShowPwd:false
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("search");

          this.$API.staff.findByName(this.searchForm.name).then(res=>{
            // console.log(res);
            if(res.data.length !== 0){
              this.formatStaffList(res.data)
              this.total = res.total
            }else{
              this.$message.info("无相关搜索结果")
            }
          })
          
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$refs[formName].clearValidate()

      this.getStaffList()
    },
    searchByRole(){
      if(this.searchForm.role === ""){
        this.$message.info("还未选择相应身份")
      }else{
        this.$API.staff.findByRole(this.searchForm.role).then(res=>{
          if(res.data.length === 0){
            this.$message.info("暂无搜索结果")
          }else{
            this.total = res.total
            this.formatStaffList(res.data)
            this.searchForm.role = ""
          }
        })
      }
    },
    // 提交员工表单并检验表单有效性
    submitStaffForm(formName){
      // console.log(this.$refs[formName]);
      this.$refs[formName].validate(async valid=>{
        if(valid){
          console.log('form is valid');
          await this.addStaff()
        }else{
          console.log('error');
          return false
        }
      })
    },
    // 取消表单填写时 清除表单验证并初始化staffForm
    handleCancel(){
      this.dialogStaffVisible = false
      this.staffInit()
    },
    // 新增与编辑员工信息
    async addStaff(){
      this.loading = true
      if(this.staffForm.id == ""){
        // 新增
        this.staffForm.createdTime = formatTime(Date.now())

        let ret = await this.$API.staff.create(this.staffForm)
      }else{
        // 更新员工信息
        this.staffForm.updateTime = formatTime(Date.now())
        await this.$API.staff.update(this.staffForm)
      }
      

      this.staffInit()
    },
    staffInit(){
      this.loading = false
      this.dialogStaffVisible = false
      this.$refs.staffForm.clearValidate()
      this.staffForm = {
        id:"",
        name:"",
        phoneNumber:"",
        password:"",
        role:"",
        createdTime:""
      }

      this.getStaffList()
    },
    // 获取员工列表
    async getStaffList(){
      let ret = await this.$API.staff.getList(this.currentPage,this.pageSize,this.role)

      // console.log(ret);
      this.total = ret.total

      this.formatStaffList(ret.data)
    },
    // 对员工列表进行格式化处理
    formatStaffList(arr){
      arr.forEach((item)=>{
        if(item.role === "doctor"){
          item.role = "医生"
        }else if(item.role === "repair"){
          item.role = "维修师傅"
        }else if (item.role === "committee"){
          item.role = "居委会"
        }else if(item.role === "admin"){
          item.role = "管理员"
        }

        if(!item.updateTime){
          item.updateTime = "暂无更新"
        }
        item = Object.assign(item,{hiddenPassword:'******',showPassword:false})
      })
      this.staffList = arr
    },
    // 处理列表序号
    handelIndex(index){
      return index + (this.currentPage - 1) * this.pageSize + 1
    },
    // 处理当前页并获取新列表
    handleCurrentPage(currentPage){
      this.currentPage = currentPage
      this.getStaffList()
    },
    // 控制登录密码的显示情况
    view(index,row){
      console.log(index,"111");
      
      this.staffList[index].showPassword = !row.showPassword

    },
    // 编辑员工信息
    handleEdit(index,row){
      this.staffForm = row
      this.dialogStaffVisible = true
    },
    // 处理删除员工信息
    async handleDelete(index,row){
      const {_id} = row 

      await this.$API.staff.deleteById(_id)

      this.getStaffList()
    }
  },
  created() {
    this.getStaffList()
  }
}
</script>

<style lang='less' scoped>
  
  .searchContainer{
    .el-input{
      width: 240px;
      margin-right: 15px;
    }
  }
  .operationBox{
    .el-button{
      margin-right: 15px;
    }

  }
  .paginationBox{
    .el-button{
      margin-right: 15px;
    }
    .el-table{
      margin: 15px 0;
    }
    .el-icon-view{
      margin-left:10px;
    }
  }
</style>